package net.nohaven.proj.javeau.fs.crypt;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;

import net.nohaven.proj.javeau.crypt.streams.PhelixInputStream;
import net.nohaven.proj.javeau.fs.exceptions.EntityNotFoundException;
import net.nohaven.proj.javeau.fs.model.FSFile;

public final class CFSFile implements FSFile {
	private File realFile;
	private String name;
	private byte[] key, iv, mac;

	protected CFSFile(File realFile, String name, byte[] key, byte[] iv,
			byte[] mac) {
		this.realFile = realFile;
		this.name = name;
		this.key = key;
		this.iv = iv;
		this.mac = mac;
	}

	protected void delRealFile() {
		realFile.delete();
	}

	protected void setName(String name) {
		this.name = name;
	}

	public InputStream getContent() throws EntityNotFoundException {
		try {
			InputStream is = new FileInputStream(realFile);
			return new PhelixInputStream(is, key, iv, realFile.length());
		} catch (FileNotFoundException e) {
			throw new EntityNotFoundException();
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		}
	}

	public long getSize() {
		return realFile.length();
	}

	public boolean canWrite() {
		return true;
	}

	public Date getModificationDate() {
		return new Date(realFile.lastModified());
	}

	public String getName() {
		return name;
	}

	protected byte[] getIv() {
		return iv;
	}

	protected byte[] getMac() {
		return mac;
	}
}
